package com.zrx.app.android.modules;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.StringCodec;
import com.zrx.app.android.R;
import com.zrx.app.android.UTIL.ImageUTIL;
import com.zrx.app.android.UTIL.RemoteConn;
import com.zrx.app.android.UTIL.ZRXUTIL;
import com.zrx.app.android.ZRXApplication;
import com.zrx.app.android.fragment.FragmentShowbackReason;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by $HL on 2017/9/23.
 */

public abstract class BaseModule_two implements Serializable {
    private static final String TAG = "BaseModule_two";
    static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    static DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public abstract String getMainURL();
    public abstract void startActivity(Context context, JSONObject record);
    private String result_Reason = "";

    private static final String SAVE_PIC_PATH= Environment.getExternalStorageState().equalsIgnoreCase(Environment.MEDIA_MOUNTED) ? Environment.getExternalStorageDirectory().getAbsolutePath():"/mnt/sdcard";//保存到SD卡
    private static final String SAVE_REAL_PATH = SAVE_PIC_PATH+" /good/savePic";//保存的确切位置

    private  String mainURL2="/tango/listAddtionalDataPendingRecords";

    public View getView(final JSONObject record, final ViewGroup vg) {
        final LayoutInflater inflater = (LayoutInflater) ZRXApplication.getAppContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.layout_list_element_two, vg,false);

        TextView useTime_label = (TextView)view.findViewById(R.id.useTime_label);
        TextView lbName = (TextView) view.findViewById(R.id.label_name_two);
        TextView lbIdCardNum = (TextView) view.findViewById(R.id.label_idCardNum_two);
        TextView lbTel = (TextView) view.findViewById(R.id.label_tel_two);
        TextView lbState = (TextView) view.findViewById(R.id.label_state_two);
        TextView lbUsetime = (TextView) view.findViewById(R.id.label_usetime);
        TextView lbBackreason = (TextView) view.findViewById(R.id.label_back_reason);
       /* Log.e("传入数据",String.valueOf(record));*/
        GradientDrawable drawable = new GradientDrawable();
        view.setBackground(drawable);
        drawable.setShape(GradientDrawable.RECTANGLE);
        drawable.setStroke(0, Color.BLACK);
        drawable.setCornerRadius(8);
        try {
            JSONObject basicData =null;
            if(record.containsKey("basicData"))
                basicData=record.getJSONObject("basicData");
           /* Log.e("传入数据2",String.valueOf(basicData));*/
            String backReason="未知";
            String name="未知";
            String idCardNum="未知";
            String tel="未知";
            String state="未知";

            if(basicData!=null){
                if(basicData.containsKey("借款人情况_借款人姓名")){
                    name=basicData.getString("借款人情况_借款人姓名");
             /*   Log.e("申请人",name);*/
                }
                else if(basicData.containsKey("融资人")){
                    name=basicData.getString("融资人");
                }
                if(basicData.containsKey("身份证号")) {
                        idCardNum = basicData.getString("身份证号");
                    if(idCardNum.length()>11)
                        idCardNum=idCardNum.substring(0,6)+"********"+idCardNum.substring(14);
                }
                if(basicData.containsKey("手机号")) {
                    tel = basicData.getString("手机号");
                    if(tel.length()>4)
                        tel=tel.substring(0,tel.length()-4)+"****";
                }
            }

            String rawState = record.getString("state");
            drawable.setColor(ZRXUTIL.translateStateToColor(rawState));
            if(record.containsKey("state")){
                state = ZRXUTIL.translateState(rawState);
            }
            if(record.containsKey("modifiedDate")){
                    String modifiedDate = "未知";
                    if(record.containsKey("modifiedDate"))
                        modifiedDate = sdf.format(record.getDate("modifiedDate"));
                Date date = new Date();
                String nowDate = sdf.format(date);
                Date d1 = df.parse(modifiedDate);
                Date d2 = df.parse(nowDate);
                long diff = d2.getTime() - d1.getTime();//这样得到的差值是微秒级别
                long days = diff / (1000 * 60 * 60 * 24);
                long hours = (diff-days*(1000 * 60 * 60 * 24))/(1000* 60 * 60);
                long minutes = (diff-days*(1000 * 60 * 60 * 24)-hours*(1000* 60 * 60))/(1000* 60);
                if ("CAR_DONE".equals(record.getString("state"))){
                    useTime_label.setText("放车完成时间");
                    lbUsetime.setText(modifiedDate.toString());
                }
                else lbUsetime.setText(String.valueOf(""+days+"天"+hours+"小时"+minutes+"分"));
            }
            if(record.containsKey("comment")){
                backReason = record.getString("comment");
              /*  Log.e("backreason",String.valueOf(backReason));*/
            }

            lbName.setText(String.valueOf(name));
            lbIdCardNum.setText(String.valueOf(idCardNum));
            lbTel.setText(String.valueOf(tel));
            lbState.setText(String.valueOf(state));
            lbBackreason.setText(String.valueOf(backReason));

            final String finalName = name;
            view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        try {
                            JSONObject loanInfo = null;
                            JSONObject loan_pics = null;
                            String id = record.getString("id");
                            Log.e("id11",id.toString());
                            JSONObject re = RemoteConn.getInstance().listReason(id.toString());
                            if (re != null){
                                JSONObject data = (JSONObject) re.get("data");
                                if (data != null){
                                JSONArray data_pre = (JSONArray) data.get("previous");
                                    if (data_pre != null){
                                for (int i = 0; i < data_pre.size(); i++) {
                                    JSONObject result_comment = data_pre.getJSONObject(i);
                                    result_Reason = result_Reason +  ZRXUTIL.translateState(result_comment.getString("state")).toString() + "     ";
                                    result_Reason = result_Reason + result_comment.getString("comment") + "     ";
                                    String reason_Time = sdf.format(result_comment.getDate("modifiedDate"));
                                    result_Reason = result_Reason + reason_Time.toString() + "\n";
                                }
                                    }
                                    else result_Reason = "";
                                }
                               else result_Reason = "";
                            }
                          Dialog dia = new Dialog(vg.getContext(), R.style.edit_AlertDialog_style);
                            dia.setContentView(R.layout.dialog_reasonandpicture_list);
                            final ImageView imageView = (ImageView) dia.findViewById(R.id.reason_picture);
                            /*imageView.setImageResource(R.mipmap.logo);*/
                            TextView textview = (TextView)dia.findViewById(R.id.reason_text);
                            textview.setText(result_Reason.toString());
                            result_Reason = "";
                            String state=record.getString("state");
                            Log.e("stata",state.toString());

                            if(record.containsKey("loanInfo"))
                                loanInfo = record.getJSONObject("loanInfo");
                            if (loanInfo != null){
                                loan_pics = loanInfo.getJSONObject("loan_pics");
                            }
                            if (loan_pics != null){
                                String fileId = loan_pics.getString("放款银行凭证照片");
                                Log.e("照片ID",fileId.toString());
                                File dir=new File(ZRXUTIL.path + "银行放款凭证");
                                if(!dir.exists())
                                    dir.mkdirs();
                                String filePath=ZRXUTIL.path + "-" + "银行放款凭证" + "-" + finalName.toString();
                                File file=new File(filePath);
                                if(file.exists()){
                                    imageView.setImageURI(Uri.fromFile(file));
                                }else{
                                    imageView.setImageResource(R.drawable.loading);
                                    final String _fileId=fileId;
                                    final String _filePath=filePath;
                                    AsyncTask at=new AsyncTask() {
                                        @Override
                                        protected Object doInBackground(Object[] params) {
                                            return RemoteConn.getInstance().getFile(_fileId, _filePath);//_fileId这个是获取到的id,_filePath保存的路径
                                        }

                                        @Override
                                        protected void onPostExecute(Object o) {
                                            super.onPostExecute(o);
                                            if(Boolean.TRUE.equals(o)){
                                                imageView.setImageBitmap(ImageUTIL.fitToImageView(imageView,_filePath));
                                            }
                                            else{
                                                imageView.setImageResource(R.drawable.fail);
                                            }
                                        }
                                    };
                                    at.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,new Object());
                                }
                            }
                            dia.setCanceledOnTouchOutside(true); // Sets whether this dialog is
                            Window w = dia.getWindow();
                            WindowManager.LayoutParams lp = w.getAttributes();
                            lp.x = 0;
                            lp.y = 40;
                            dia.onWindowAttributesChanged(lp);
                            dia.show();
                          /*  LayoutInflater inflater=LayoutInflater.from(vg.getContext());
                            View dialog=inflater.inflate(R.layout.dialog_reasonandpicture_list, null);
                            GridLayout content = (GridLayout)dialog.findViewById(R.id.dialog_list_content);
                            AlertDialog.Builder ad = new AlertDialog.Builder(v.getContext());
                            TextView textView = new TextView(vg.getContext());
                            textView.setText(result_Reason.toString());
                            content.addView(textView);
                            ad.setView(dialog);

                            ad.setNegativeButton("确认", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            });
                            ad.show();
                            */
                           /* final AlertDialog.Builder normalDialog =
                                    new AlertDialog.Builder(vg.getContext());
                            normalDialog.setTitle("返回原因列表");
                            normalDialog.setMessage(result_Reason.toString());
                            normalDialog.setPositiveButton("确定",
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                        }
                                    });
                            normalDialog.show();*/
                        }catch (Exception e){
                            Log.e(TAG,e.getMessage());
                        }
                }
            });

        } catch (Exception e) {
            Log.d(TAG, e.getMessage());
        }
        return view;
    }



    public abstract String getModuleName();


    protected Object doInbackgroud_reason(){
        RemoteConn http = RemoteConn.getInstance();
        return http.fetchData_reason(mainURL2);
    }

    protected void getDate(Object o){
        if (o != null && o instanceof JSONObject) {
            JSONArray arr = ((JSONObject) o).getJSONArray("content");
        /*    totalPageNum = ((JSONObject) o).getIntValue("totalPages");
            pageNum = ((JSONObject) o).getIntValue("number");*/
        }
    }

    public static void saveFile(Bitmap bm, String fileName, String path) throws IOException {
        String subForder = SAVE_REAL_PATH + path;
        File foder = new File(subForder);
        if (!foder.exists()) {
            foder.mkdirs();
        }
        File myCaptureFile = new File(subForder, fileName);
        if (!myCaptureFile.exists()) {
            myCaptureFile.createNewFile();
        }
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
        bos.flush();
        bos.close();
    }


}
